# 处理 api 响应
import requests
import plotly.express as px

    # 执行 api 调用并查看响应
url = "https://api.github.com/search/repositories"
url += "?q=language:python+sort:stars+stars:>10000" ## 太长所以分成了两行
headers = {"Accept":"application/vnd.github.v3+json"}
r = requests.get(url,headers)
print(f"Status code: {r.status_code}")
    # 处理结果 将响应转换成字典
response_dict = r.json()
print(f"Complete results : {not response_dict["incomplete_results"]}")

    #处理仓库有关信息
repo_dicts = response_dict["items"]
repo_names, stars = [],[]
for repo_dict in repo_dicts:
    repo_names.append(repo_dict["name"])
    stars.append(repo_dict["stargazers_count"])

#可视化
fig = px.bar(x=repo_names,y=stars)
fig.show()

    # 设置图形样式
title = "Most-Starred Python Projects on Github"
labels = {"x": "Repository", "y": "Stars"}
fig = px.bar(x=repo_names,y=stars,title=title,labels=labels)
fig.update_layout(title_font_size=28,xaxis_title_font_size=20,yaxis_title_font_size=20)
fig.show()

# 添加定制工具提示
    #处理仓库有关信息
repo_dicts = response_dict["items"]
repo_names, stars, hover_texts = [],[],[]
for repo_dict in repo_dicts:
    repo_names.append(repo_dict["name"])
    stars.append(repo_dict["stargazers_count"])
    #创建悬停文本
    owner = repo_dict["owner"]["login"]
    description = repo_dict["description"]
    hover_text = f"{owner}<br />{description}"
    hover_texts.append(hover_text)

    # 设置图形样式
title = "Most-Starred Python Projects on Github"
labels = {"x": "Repository", "y": "Stars"}
fig = px.bar(x=repo_names,y=stars,title=title,labels=labels,hover_name=hover_texts)
fig.update_layout(title_font_size=28,xaxis_title_font_size=20,yaxis_title_font_size=20)
fig.show()

# 添加可点击的链接
    #处理仓库有关信息
repo_dicts = response_dict["items"]
repo_links, stars, hover_texts = [],[],[]
for repo_dict in repo_dicts:
    repo_name = repo_dict["name"]
    repo_url = repo_dict["html_url"]
    repo_link = f"<a href='{repo_url}'>{repo_name}</a>"
    repo_links.append(repo_link)
    stars.append(repo_dict["stargazers_count"])
    #创建悬停文本
    owner = repo_dict["owner"]["login"]
    description = repo_dict["description"]
    hover_text = f"{owner}<br />{description}"
    hover_texts.append(hover_text)

    # 设置图形样式
title = "Most-Starred Python Projects on Github"
labels = {"x": "Repository", "y": "Stars"}
fig = px.bar(x=repo_links,y=stars,title=title,labels=labels,hover_name=hover_texts)
fig.update_layout(title_font_size=28,xaxis_title_font_size=20,yaxis_title_font_size=20)
fig.show()

# 定制标记颜色
fig.update_layout(title_font_size=28,xaxis_title_font_size=20,yaxis_title_font_size=20)
fig.update_traces(marker_color="SteelBlue",marker_opacity = 0.6)
fig.show()

